<template>
  <div>
    <div class="card comment-form">
      <div class="card-block">
        <textarea v-model="body" class="form-control" placeholder="Write a comment..." rows="3"></textarea>
      </div>
      <div class="card-footer">
        <img :src="user.image" class="comment-author-img" />
        <el-button :loading="submitCommentLoading" type="primary" class="btn btn-sm btn-primary" @click="submitComment">
        Post Comment
        </el-button>
      </div>
    </div>

    <div
      class="card"
      v-for="(comment, index) in comments"
      :key="comment.id"
    >
      <div class="card-block">
        <p class="card-text">{{ comment.body }}</p>
      </div>
      <div class="card-footer">
        <nuxt-link class="comment-author" :to="{
          name: 'profile',
          params: {
            username: comment.author.username
          }
        }">
          <img :src="comment.author.image" class="comment-author-img" />
        </nuxt-link>
        &nbsp;
        <nuxt-link class="comment-author" :to="{
          name: 'profile',
          params: {
            username: comment.author.username
          }
        }">
          {{ comment.author.username }}
        </nuxt-link>
        <span class="date-posted">{{ comment.createdAt | date('MMM DD, YYYY') }}</span>
        <span class="mod-options" v-if="comment.author.username === user.username" @click="deleteComment(comment.id, index)"><i class="ion-trash-a"></i></span>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getComments, postComment, deleteComment } from '@/api/article'

export default {
  name: 'ArticleComments',
  props: {
    article: {
      type: Object,
      required: true
    }
  },
  computed: {
    ...mapState(['user'])
  },
  data () {
    return {
      comments: [], // 文章列表
      body: '',
      submitCommentLoading: false
    }
  },
  async mounted () {
    const { data } = await getComments(this.article.slug)
    this.comments = data.comments
  },
  methods: {
    async submitComment() {
      if(!this.body) {
        this.$message.warning('请填写评论内容')
        return
      }
      this.submitCommentLoading = true
      const { data } = await postComment(this.article.slug ,{
        comment: {
          body: this.body
        }
      })
      this.submitCommentLoading = false
      this.comments.unshift(data.comment)
      this.body = ''
    },
    deleteComment(id, index) {
      deleteComment(this.article.slug, id).then(res => {
        this.comments.splice(index, 1)
      })
    }
  }
}
</script>

<style>

</style>
